package Props
{
	import DataStore.DataSource;
	import DrawEngine.DrawInfo;
	import SceneUnit.PlayScene;
	import SceneUnit.SceneManager;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.utils.Dictionary;

	public class PropManager
	{
		public static var Propes:Dictionary;
		public static var propDrawInfos:Vector.<DrawInfo>;
		public static var propIds:Vector.<int>;
		
		public static var xmlLoader:URLLoader;
		public static var loader:Loader;
		
		public static var PropReady:Boolean;
		
		public function PropManager()
		{
		}
		
		//道具管理器
		//初始化，载入需要的道具图块
		public static function Init():void
		{ 
			var urlXmlFile:String = DataSource.propsUrl;
			xmlLoader = new URLLoader();
			Propes = new Dictionary();
			propDrawInfos = new Vector.<DrawInfo>();
			propIds = new Vector.<int>();
			xmlLoader.addEventListener(Event.COMPLETE,OnLoadXml);
			xmlLoader.load(new URLRequest(urlXmlFile));	
		}
		
		//道具图片资源是否准备好
		public static function GetFlag():Boolean
		{
			return PropReady;
		}
		
		public static function OnLoadXml(e:Event):void
		{
			var loader2:URLLoader = e.target as URLLoader;
			var xml:XML = new XML(loader2.data);
			xmlLoader.removeEventListener(Event.COMPLETE, OnLoadXml);		  
			
			for each(var el:XML in xml.Frame)
			{
				var x:int = parseInt(el.@X[0]);
				var y:int = parseInt(el.@Y[0]);
				var w:int = parseInt(el.@Width[0]);
				var h:int = parseInt(el.@Height[0]);
				var name:String = el.@Name[0];
				var id:int = parseInt(el.@Index[0]);
				var offsetX:int = parseInt(el.@OffsetX[0]);
				var offsetY:int = parseInt(el.@OffsetY[0]);				
				propDrawInfos.push(new DrawInfo(name,id,x,y,w,h,offsetX,offsetY));			
			}		
						
			var loaderTemp:Loader = new Loader();
			loaderTemp.contentLoaderInfo.addEventListener(Event.COMPLETE, OnLoadImg);
			var st:String = "Resource2/Image/Props/CommProp1.png";// DataSource.propImg;
			//loaderTemp.load(new URLRequest(DataSource.propImg));			
		}
		
		public static function OnLoadImg(e:Event):void
		{
			var loader2:Loader = (e.target.loader) as Loader;			
			var bmpData:BitmapData = (loader2.content as Bitmap).bitmapData;
			
			for each(var item:DrawInfo in propDrawInfos)
			{
				var prop:BitmapData = new BitmapData(item.wRect, item.hRect);				
				prop.copyPixels(bmpData, new Rectangle(item.xRect,item.yRect,item.wRect,item.hRect), new Point(item.xP, item.yP));				
			    Propes[item.Id] = prop;		
			}
			loader2.contentLoaderInfo.removeEventListener(Event.COMPLETE, OnLoadImg);		
			PropReady = true;
		}
	}
}